
# create temp folder and run test
$tempMainFolder = (new-guid).guid
$sourceFolder = "$tempMainFolder\source"
$targetFolder = "$tempMainFolder\target"
New-Item -Path $tempMainFolder -ItemType Directory -Force

function CreateSourceAndTargetFolder {
    New-Item -Path $sourceFolder -ItemType Directory -Force
    New-Item -Path $targetFolder -ItemType Directory -Force
}
function Assert {
    param (
        $A,
        $B,
        $msg
    )
    if ($A -ne $B) {
        throw $msg
    }
}
function TestExist {
    param(
        [string]$folderPath,
        [string[]]$exist,
        [string[]]$nonExist
    )
    # exist
    foreach ($item in $exist) {
        $itemPath = Join-Path $folderPath $item
        if (!(Test-Path -Path $itemPath)) {
            Write-Error "TestExist.exist: $item" 
        }
    }
    # nonExist
    foreach ($item in $nonExist) {
        $itemPath = Join-Path $folderPath $item
        if (Test-Path -Path $itemPath) {
            Write-Error "TestExist.nonExist: $item" 
        }
    }
}

# ok
function ok {
    CreateSourceAndTargetFolder
    $fileNames = @("1.txt", "2.txt", "log\log123.txt", "log2\xx\1.txt", "log2\xx\2.txt")
    foreach ($fileName in $fileNames) {
        New-Item -Path "$sourceFolder\$fileName" -ItemType File -Force
    }
    $ignore = @"
log
**\2.txt
"@
    .\backup.ps1 -sourceFolder $sourceFolder -targetFolder $targetFolder -backupVersionName [yyyyMMddHHmmss] -maxBackupCount 2 -backupIgnore $ignore
    Start-Sleep -Milliseconds 1100
    .\backup.ps1 -sourceFolder $sourceFolder -targetFolder $targetFolder -backupVersionName [yyyyMMddHHmmss] -maxBackupCount 2 -backupIgnore $ignore
    Start-Sleep -Milliseconds 1100
    .\backup.ps1 -sourceFolder $sourceFolder -targetFolder $targetFolder -backupVersionName [yyyyMMddHHmmss] -maxBackupCount 2 -backupIgnore $ignore
    
    Assert (Get-ChildItem -Path $targetFolder).Count 2 'ok.targetFolder.Count'

    $first = (Get-ChildItem -Path $targetFolder -Directory) | Select-Object -First 1
    Assert (Get-ChildItem -Path $first.FullName).Count 3 'ok.first.Count'

    TestExist $first.FullName @("1.txt", "2.txt", "log2\xx\1.txt") @("log", "log2\xx\2.txt")
    Remove-Item $tempMainFolder -Force -Recurse
}
ok

# error
function error_targetInSource {
    CreateSourceAndTargetFolder
    $targetFolder = "$sourceFolder\a"
    $fileNames = @("1.txt")
    foreach ($fileName in $fileNames) {
        New-Item -Path "$sourceFolder\$fileName" -ItemType File -Force
    }

    try {
        .\backup.ps1 -sourceFolder $sourceFolder -targetFolder $targetFolder -backupVersionName [yyyyMMddHHmmss] -maxBackupCount 2 -backupIgnore "log"
    }
    catch {
        Assert "$($_.Exception.Message)".Contains("The backup directory should not be under the source directory") $True $($_.Exception.Message)
    }
    Remove-Item $tempMainFolder -Force -Recurse
}
error_targetInSource
